<!DOCTYPE html>
<html lang="zh-CN">





<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/blog/img/favicon.png">
  <link rel="icon" type="image/png" href="/blog/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
    <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
  
  <meta name="theme-color" content="#35495e">
  <meta name="description" content="小菜头的博客，主要记录学习笔记，包含：html,css,javascript,jQuery,vue等">
  <meta name="author" content="A-cai">
  <meta name="keywords" content="html,css,javascript,jQuery,vue">
  <title>框架中列表组件key的作用 - A-cai的blog</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/blog/lib/hint/hint.min.css" />

  
    <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/atom-one-dark.min.css" />
  

  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_yg9cfy8wd6.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">


<link  rel="stylesheet" href="/blog/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script  src="/blog/js/utils.js" ></script>
<meta name="generator" content="Hexo 4.2.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/blog/">&nbsp;<strong>A-cai的学习笔记</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner intro-2" id="background" parallax=true
         style="background: url('/blog/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container text-center white-text fade-in-up">
            <span class="h2" id="subtitle">
              
            </span>

            
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2020-06-26 14:04">
      2020年6月26日 下午
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      760 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      9
       分钟
    </span>
  

  
  
    
      <!-- 不蒜子统计文章PV -->
      <span id="busuanzi_container_page_pv" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="busuanzi_value_page_pv"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <div class="post-content mx-auto" id="post">
            
              <p class="note note-info">
                
                  本文最后更新于：2020年4月2日 下午
                
              </p>
            
            <article class="markdown-body">
              <h1 id="写-React-Vue-项目时为什么要在列表组件中写-key，其作用是什么"><a href="#写-React-Vue-项目时为什么要在列表组件中写-key，其作用是什么" class="headerlink" title="写 React / Vue 项目时为什么要在列表组件中写 key，其作用是什么"></a>写 React / Vue 项目时为什么要在列表组件中写 key，其作用是什么</h1><blockquote>
<p>当 Vue 正在更新使用 v-for 渲染的元素列表时，它默认使用“就地更新”的策略。如果数据项的顺序被改变，Vue 将不会移动 DOM。 元素来匹配数据项的顺序，而是就地更新每个元素，并且确保它们在每个索引位置正确渲染。这个类似 Vue 1.x 的 track-by=”$index”。</p>
</blockquote>
<p>这个默认的模式是高效的，但是只适用于不依赖子组件状态或临时 DOM 状态 (例如：表单输入值) 的列表渲染输出。</p>
<ul>
<li>避免对节点「就地复用」</li>
</ul>
<p>需要修改的节点位置没有改变，是内容更新了，这虽然提高了复用性能，但是往往在复杂的表单会导致状态出现错位。也不会产生过度效果</p>
<ul>
<li>key相当于每个vnode 的唯一id，我们可以依靠<code>key</code>，更快更精确的知道oldVnode中对应的vnode节点。</li>
</ul>
<p>带key就不会使用就定复用了，在sameNode函数<code>a.key===b.key</code>对比中可以避免就地复用的情况。</p>
<p>我们可以利用key的唯一性来更快获取到对应节点，比遍历更快。</p>
<h2 id="什么是diff算法？"><a href="#什么是diff算法？" class="headerlink" title="什么是diff算法？"></a>什么是diff算法？</h2><p>要渲染真实的DOM的开销很大，因为改变真实dom，会当值整个dom树的重绘和回流。我们需要渲染真实dom的时候往往会把生成一个<code>虚拟节点</code> virtual DOM，当virtual dom某个节点的数据改变后生成一个新的Vnode，然后将Vnode和oldVnode对比，当然有不同的地方教就直接修改在真实DOM上，然后是oldVnode=Vnode</p>
<ul>
<li>真实DOM</li>
</ul>
<div class="hljs"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>123<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></code></pre></div>

<ul>
<li>virtual DOM （虚拟DOM）</li>
</ul>
<div class="hljs"><pre><code class="hljs vim">var Vnode=&#123;
    <span class="hljs-keyword">ta</span><span class="hljs-variable">g:</span><span class="hljs-string">'div'</span>,
    children:[&#123;
        <span class="hljs-keyword">ta</span><span class="hljs-variable">g:</span><span class="hljs-string">'p'</span>,tex<span class="hljs-variable">t:</span><span class="hljs-string">'123'</span>
    &#125;]
    
&#125;</code></pre></div>

<h3 id="diff的比较方式"><a href="#diff的比较方式" class="headerlink" title="diff的比较方式"></a>diff的比较方式</h3><p>在同层级进行，不会跨层级比较</p>
<p>oldDOM</p>
<div class="hljs"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>123<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></code></pre></div>

<p>newDOM</p>
<div class="hljs"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>2222<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></code></pre></div>

<p><img src="https://segmentfault.com/img/bVbvtvU?w=404&h=225" srcset="/blog/img/loading.gif" alt="clipboard.png"></p>
<ul>
<li>先对比DIV，发现两个DIV不对等</li>
<li>查看DIV的子元素P、SPAN，发现不对等</li>
<li>查看P、SPAN没有子元素，则移除P，增加SPAN</li>
</ul>
<p><img src="https://segmentfault.com/img/bVbvtwL?w=920&h=680" srcset="/blog/img/loading.gif" alt="clipboard.png"></p>
<p>现在我们来看看在进行替换</p>
<h4 id="对比节点函数"><a href="#对比节点函数" class="headerlink" title="对比节点函数"></a>对比节点函数</h4><div class="hljs"><pre><code class="hljs reasonml"><span class="hljs-keyword">function</span> patch(oldVnode, vnode) &#123;
  <span class="hljs-comment">// 对比是否相等</span>
  <span class="hljs-keyword">if</span> (same<span class="hljs-constructor">Vnode(<span class="hljs-params">oldVnode</span>, <span class="hljs-params">vnode</span>)</span>) &#123;
    patch<span class="hljs-constructor">Vnode(<span class="hljs-params">oldVnode</span>, <span class="hljs-params">vnode</span>)</span>
  &#125; <span class="hljs-keyword">else</span> &#123;
    const oEl = oldVnode.el <span class="hljs-comment">// 当前oldVnode对应的真实元素节点</span>
    <span class="hljs-keyword">let</span> parentEle = api.parent<span class="hljs-constructor">Node(<span class="hljs-params">oEl</span>)</span> <span class="hljs-comment">// 父元素</span>

    create<span class="hljs-constructor">ELe(<span class="hljs-params">vnode</span>)</span> <span class="hljs-comment">// 为vnode生成新的元素</span>

    <span class="hljs-keyword">if</span> (parentEle !== null) &#123;
      api.insert<span class="hljs-constructor">Before(<span class="hljs-params">parentEle</span>, <span class="hljs-params">vnode</span>.<span class="hljs-params">el</span>, <span class="hljs-params">api</span>.<span class="hljs-params">nextSibling</span>(<span class="hljs-params">oEl</span>)</span>) <span class="hljs-comment">// 将新的元素添加到父元素中</span>
      api.remove<span class="hljs-constructor">Child(<span class="hljs-params">parentEle</span>, <span class="hljs-params">oldVnode</span>.<span class="hljs-params">el</span>)</span> <span class="hljs-comment">// 移除以前的元素</span>
    &#125;
  &#125;

  return vnode
&#125;</code></pre></div>

<h4 id="判断两者是否相同函数"><a href="#判断两者是否相同函数" class="headerlink" title="判断两者是否相同函数"></a>判断两者是否相同函数</h4><div class="hljs"><pre><code class="hljs reasonml"><span class="hljs-keyword">function</span> same<span class="hljs-constructor">Vnode(<span class="hljs-params">a</span>, <span class="hljs-params">b</span>)</span> &#123;
  return (
    a.key<span class="hljs-operator"> === </span>b.key<span class="hljs-operator"> &amp;&amp; </span><span class="hljs-comment">// 对比key</span>
    a.tag<span class="hljs-operator"> === </span>b.tag<span class="hljs-operator"> &amp;&amp; </span><span class="hljs-comment">// 对比标签名</span>
    a.isComment<span class="hljs-operator"> === </span>b.isComment<span class="hljs-operator"> &amp;&amp; </span><span class="hljs-comment">// 是否为注释节点</span>
    is<span class="hljs-constructor">Def(<span class="hljs-params">a</span>.<span class="hljs-params">data</span>)</span><span class="hljs-operator"> === </span>is<span class="hljs-constructor">Def(<span class="hljs-params">b</span>.<span class="hljs-params">data</span>)</span><span class="hljs-operator"> &amp;&amp; </span><span class="hljs-comment">// 是否定义了data，或者其他属性</span>
    same<span class="hljs-constructor">InputType(<span class="hljs-params">a</span>, <span class="hljs-params">b</span>)</span> <span class="hljs-comment">//判断是当&lt;Input&gt;时 是否type相同</span>
  )
&#125;</code></pre></div>
            </article>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" target="_blank" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <div class="post-prev col-6">
                    
                    
                      <a href="/blog/2020/06/26/Object.defineProperty%E7%BC%BA%E9%99%B7/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Object.defineProperty缺陷</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </div>
                  <div class="post-next col-6">
                    
                    
                      <a href="/blog/2020/06/26/%E5%A6%82%E4%BD%95%E5%AE%9E%E7%8E%B0token%E5%8A%A0%E5%AF%86/">
                        <span class="hidden-mobile">如何实现token加密</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </div>
                </div>
              
            </div>

            
              <!-- Comments -->
              <div class="comments" id="comments">
                
                

              </div>
            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  

  <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a>
      <i class="iconfont icon-love"></i>
      <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener">
        <span>Fluid</span></a>
    </div>
    

    

    
  </div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/blog/js/debouncer.js" ></script>
<script  src="/blog/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/blog/js/lazyload.js" ></script>
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/blog/js/clipboard-use.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: 'article.markdown-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "框架中列表组件key的作用&nbsp;",
      ],
      cursorChar: "|",
      typeSpeed: 70,
      loop: true,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/blog/js/local-search.js" ></script>
  <script>
    var path = "/blog/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>







  
  
    <script>
      !function (e, t, a) {
        function r() {
          for (var e = 0; e < s.length; e++) s[e].alpha <= 0 ? (t.body.removeChild(s[e].el), s.splice(e, 1)) : (s[e].y--, s[e].scale += .004, s[e].alpha -= .013, s[e].el.style.cssText = "left:" + s[e].x + "px;top:" + s[e].y + "px;opacity:" + s[e].alpha + ";transform:scale(" + s[e].scale + "," + s[e].scale + ") rotate(45deg);background:" + s[e].color + ";z-index:99999");
          requestAnimationFrame(r)
        }

        function n() {
          var t = "function" == typeof e.onclick && e.onclick;
          e.onclick = function (e) {
            t && t(), o(e)
          }
        }

        function o(e) {
          var a = t.createElement("div");
          a.className = "heart", s.push({
            el: a,
            x: e.clientX - 5,
            y: e.clientY - 5,
            scale: 1,
            alpha: 1,
            color: c()
          }), t.body.appendChild(a)
        }

        function i(e) {
          var a = t.createElement("style");
          a.type = "text/css";
          try {
            a.appendChild(t.createTextNode(e))
          } catch (t) {
            a.styleSheet.cssText = e
          }
          t.getElementsByTagName("head")[0].appendChild(a)
        }

        function c() {
          return "rgb(" + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + ")"
        }

        var s = [];
        e.requestAnimationFrame = e.requestAnimationFrame || e.webkitRequestAnimationFrame || e.mozRequestAnimationFrame || e.oRequestAnimationFrame || e.msRequestAnimationFrame || function (e) {
          setTimeout(e, 1e3 / 60)
        }, i(".heart{width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: fixed;}.heart:after{top: -5px;}.heart:before{left: -5px;}"), n(), r()
      }(window, document);
    </script>
  













</body>
</html>
